package com.orangelife.mobile.individual.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.adapter.FatherAdapter;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.ScrollListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 快递查询结果
 * Created by YangWei
 * on 2016/3/15.
 */
public class ExpressResultFrament extends OrangeLifeBaseFragment {

    @Bind(R.id.ivExpLogo)
    ImageView ivExpLogo;
    @Bind(R.id.tvExpName)
    TextView tvExpName;
    @Bind(R.id.tvTel)
    TextView tvTel;
    @Bind(R.id.tvWeb)
    TextView tvWeb;
    @Bind(R.id.lvExpressResult)
    ScrollListView lvExpressResult;
    @Bind(R.id.llTop)
    LinearLayout llTop;
    private List<Map<String, Object>> mapList;
    private MyAdapter adapter;
    View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (view == null) {
            view = inflater.inflate(R.layout.fragment_express, container, false);
        }
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("mapList", (Serializable) mapList);
    }

    private void initView() {
        mapList = new ArrayList<>();
        adapter = new MyAdapter();
        lvExpressResult.setAdapter(adapter);
    }


    public void getSearchResutl(String expNo, String expCode) {
        String url = Constant.URL_EXPRESS_SEARCH;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("expNo", expNo);
        map.put("expCode", expCode);
        map.put("order", "desc");
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, map, handler, 0, HttpUtil.ACTION_JSON);
    }

    /**
     * 处理服务器的返回数据
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (msg.obj != null) {
                        HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map != null) {
                            int errCode = Integer.parseInt(map.get(
                                    Constant.RESULT_KEY).toString());
                            String errInfo = String.valueOf(map
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            if (errCode == Constant.RESULT_SUCCESS) {
                                HashMap<String, Object> map1 = (HashMap<String, Object>) map
                                        .get("entity");
                                /** 列表查询 */

                                int success = Integer.parseInt(map1.get("success").toString());
                                initView();
                                if (success == 0) {
                                    mapList = (List<Map<String, Object>>) map1.get("data");
                                    llTop.setVisibility(View.VISIBLE);
                                    setData(map1);
                                } else {
                                    llTop.setVisibility(View.INVISIBLE);
                                    mapList = new ArrayList<>();
                                    ToastHelper.getInstance().displayToastWithQuickClose("未查询到该快递单号的相关信息");

                                }
                                adapter.notifyDataSetChanged();

                            } else {
                                ToastHelper.getInstance()._toast(errInfo);
                            }
                        }
                    }
                    break;
                default:
                    ToastHelper.getInstance().displayToastWithQuickClose(msg.obj + "");
                    break;

            }
        }

    };

    private void setData(Map<String, Object> map) {

        String expName = map.get("company").toString();
        String tel = map.get("phone").toString();
        String expWeb = map.get("url").toString();
        String logo = map.get("ico").toString();
        ImageLoader.getInstance().displayImage(logo, ivExpLogo);
        tvExpName.setText(expName);
        tvTel.setText("查询电话：" + tel);
        tvWeb.setText("网址：" + expWeb);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private class MyAdapter extends FatherAdapter {

        @Override
        public BaseAdapter setList(List list) {
            return MyAdapter.this;
        }

        @Override
        public int getCount() {
            return mapList.size();
        }

        @Override
        public Object getItem(int position) {
            return mapList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_express_result, null);
                holder.tvContent = (TextView) convertView.findViewById(R.id.tvContent);
                holder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
                holder.vTop = convertView.findViewById(R.id.vTop);
                holder.vDown = convertView.findViewById(R.id.vDown);
                holder.ivCenter = (ImageView) convertView.findViewById(R.id.ivCenter);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String context = String.valueOf(mapList.get(position).get("context"));
            String time = String.valueOf(mapList.get(position).get("time"));
            holder.tvContent.setText(Html.fromHtml(context));
            holder.tvTime.setText(time);
            if (position == 0) {
                holder.vTop.setVisibility(View.INVISIBLE);
                holder.vDown.setVisibility(View.VISIBLE);
                holder.ivCenter.setBackgroundResource(R.drawable.ic_timeline1);
                holder.tvContent.setTextColor(getResources().getColor(R.color.text_black));
                holder.tvTime.setTextColor(getResources().getColor(R.color.text_black));
            } else {
                holder.tvContent.setTextColor(getResources().getColor(R.color.text_grey));
                holder.tvTime.setTextColor(getResources().getColor(R.color.text_grey));
                holder.vTop.setVisibility(View.VISIBLE);
                holder.ivCenter.setBackgroundResource(R.drawable.ic_timeline2);
                if (position == mapList.size() - 1) {
                    holder.vDown.setVisibility(View.INVISIBLE);
                } else {
                    holder.vDown.setVisibility(View.VISIBLE);
                }
            }


            return convertView;
        }
    }

    class ViewHolder {
        TextView tvContent;
        TextView tvTime;
        View vTop;
        View vDown;
        ImageView ivCenter;
    }

}
